$(function(){

  var pageApp = {
    init: function () {
      this.template = $('#tbody').data('template');
      this.$resultBox = $('.result-box');
      this.$resultBox.height(document.documentElement.clientHeight);
      this.$loading = $('.loading');

      this.initDatePlug();
      this.initSelect2();
      this.getPageData();
      this.lineChart();
      this.pieChart();
      this.bind();
    },
    bind: function () {
      this.$resultBox.on('click', 'th', $.proxy(this.sortTable, this));
      this.$resultBox.on('click', '.fa-square, .fa-check-square', $.proxy(this.checkboxChange, this));
      this.$resultBox.on('click', 'i.fa-step-forward', $.proxy(this.showLastPage, this));
      this.$resultBox.on('click', 'i.fa-caret-right', $.proxy(this.showNextPage, this));
      this.$resultBox.on('click', 'i.fa-caret-left', $.proxy(this.showPrePage, this));
      this.$resultBox.on('click', 'i.fa-step-backward', $.proxy(this.showFirstPage, this));
      this.$resultBox.on('change', 'select.show-num', $.proxy(this.setPageNums, this));
    },
    //当前持仓饼图
    pieChart: function () {
      var data = {"资产占比":[{"截止日":"2019-01-22","正回购":"-82.19","逆回购":"1.87","债券型":"0.64","私募专户":"2.54","基金":"6.76","现金":"12.44","债券品种":"157.94"}],"久期占比":[{"截止日":"2019-01-22","久期<=4":"18.29","久期<=2":"22.84","久期<=1":"29.28","久期<=5":"29.59"}],"行业占比":[{"截止日":"2019-01-22","银行":"0.78","材料Ⅱ":"1.39","多元金融":"1.48","房地产":"1.70","技术硬件与设备":"2.32","工业":"2.77","医疗保健设备与服务":"3.29","金融":"3.90","公用事业Ⅱ":"7.45","资本货物":"32.60","房地产Ⅱ":"34.78"}]};
      var arr = [];
      var legend_data = [];
      $.each(data['资产占比'][0], function(i, v) {
        if (i == '截止日') {
          return true;
        }
        var obj = {};
        obj.name = i;
        obj.value = Math.abs(v);
        arr.push(obj);
        legend_data.push(i);
      });

      var pie = {
        name : '资产占比',
        type : 'pie',
        radius : '38%',
        center : [ '50%', '50%' ],
        data : arr,
        label: {
          normal: {
            show: true,
            formatter: '{b}: {d}%'
          }
        },
        itemStyle : {
          emphasis : {
            shadowBlur : 10,
            shadowOffsetX : 0,
            shadowColor : 'rgba(0, 0, 0, 0.5)'
          }
        }
      };

      var myChart = echarts.init(document.getElementById('_5'));
      var option = $.extend(echartsTheme, {
        tooltip : {
          trigger : 'item',
          formatter : "{a} <br/>{b} : {c}%"
        },
        legend : {
          data : legend_data,
          x : 'center',
          y : 'bottom'
        },
        series : pie
      });
      myChart.clear();
      myChart.setOption(option);

      
      

      var arr = [];
      var legend_data = [];
      $.each(data['行业占比'][0], function(i, v) {
        if (i == '截止日') {
          return true;
        }
        var obj = {};
        obj.name = i;
        obj.value = v;
        arr.push(obj);
        legend_data.push(i);
      });

      var pie = {
        name : '债券行业占比',
        type : 'pie',
        radius : '38%',
        center : [ '50%', '50%' ],
        data : arr,
        label: {
          normal: {
            show: true,
            formatter: '{b}: {c}%'
          }
        },
        itemStyle : {
          emphasis : {
            shadowBlur : 10,
            shadowOffsetX : 0,
            shadowColor : 'rgba(0, 0, 0, 0.5)'
          }
        }
      };

      var myChart = echarts.init(document.getElementById('_6'));
      var option = $.extend(echartsTheme, {
        tooltip : {
          trigger : 'item',
          formatter : "{a} <br/>{b} : {c}%"
        },
        legend : {
          data : legend_data,
          x : 'center',
          y : 'bottom'
        },
        series : pie
      });
      myChart.clear();
      myChart.setOption(option);

    
    

      var arr = [];
      var legend_data = [];
      $.each(data['久期占比'][0], function(i, v) {
        if (i == '截止日') {
          return true;
        }
        var obj = {};
        obj.name = i;
        obj.value = v;
        arr.push(obj);
        legend_data.push(i);
      });

      var pie = {
        name : '久期占比',
        type : 'pie',
        radius : '38%',
        center : [ '50%', '50%' ],
        data : arr,
        label: {
          normal: {
            show: true,
            formatter: '{b}: {c}%'
          }
        },
        itemStyle : {
          emphasis : {
            shadowBlur : 10,
            shadowOffsetX : 0,
            shadowColor : 'rgba(0, 0, 0, 0.5)'
          }
        }
      };

      var myChart = echarts.init(document.getElementById('_7'));
      var option = $.extend(echartsTheme, {
        tooltip : {
          trigger : 'item',
          formatter : "{a} <br/>{b} : {c}%"
        },
        legend : {
          data : legend_data,
          x : 'center',
          y : 'bottom'
        },
        series : pie
      });
      myChart.clear();
      myChart.setOption(option);
    },
    //历史单位净值折线图
    lineChart: function () {
      var data = [{"截止日":"2019-01-02","指数":"1.0000","组合":"1.0000"},{"截止日":"2019-01-03","指数":"0.9984","组合":"1.0005"},{"截止日":"2019-01-04","指数":"1.0223","组合":"1.0011"},{"截止日":"2019-01-07","指数":"1.0285","组合":"1.0015"},{"截止日":"2019-01-08","指数":"1.0263","组合":"1.0025"},{"截止日":"2019-01-09","指数":"1.0367","组合":"1.0032"},{"截止日":"2019-01-10","指数":"1.0347","组合":"1.0038"},{"截止日":"2019-01-11","指数":"1.0422","组合":"1.0045"},{"截止日":"2019-01-14","指数":"1.0331","组合":"1.0047"},{"截止日":"2019-01-15","指数":"1.0534","组合":"1.0053"},{"截止日":"2019-01-16","指数":"1.0536","组合":"1.0053"},{"截止日":"2019-01-17","指数":"1.0478","组合":"1.0055"},{"截止日":"2019-01-18","指数":"1.0669","组合":"1.0059"},{"截止日":"2019-01-21","指数":"1.0728","组合":"1.0059"},{"截止日":"2019-01-22","指数":"1.0585","组合":"1.0066"}];
      if (data.length != 0) {
        var lines = [];
        var arr1 = [];
        var arr2 = [];
        $.each(data, function() {
          var obj = {};
          obj.name = new Date(this['截止日']).toString();
          obj.value = [this['截止日'], this['指数']];
          arr1.push(obj);
          
          var obj = {};
          obj.name = new Date(this['截止日']).toString();
          obj.value = [this['截止日'], this['组合']];
          arr2.push(obj);
        });
        
        var name1 = '组合';
        var name2 = '指数';
        lines.push({
          'name' : name1,
          'type' : 'line',
          'showSymbol' : false,
          'symbol': 'none',
          'hoverAnimation' : false,
          'areaStyle': {},
          'data' : arr2
        });
        
        lines.push({
          'name' : name2,
          'type' : 'line',
          'showSymbol' : false,
          'symbol': 'none',
          'hoverAnimation' : false,
          'areaStyle': {},
          'data' : arr1
        });

        var myChart = echarts.init(document.getElementById('_2'));
        var option = $.extend(echartsTheme, {
          tooltip : {
            trigger : 'axis',
            axisPointer : {
              animation : false
            }
          },
          legend : {
            data : [name1, name2],
            left: '60px',
            top: '10px'
          },
          grid : {
            bottom : '40px',
            left : '60px',
            right: '40px',
            top : '40px'
          },
          xAxis : {
            type : 'time',
            splitLine: {
              lineStyle: {
                type: 'dashed'
              }
            },
            axisLine: {
              show: false
            },
            axisTick: {
              show: false
            }
          },
          yAxis : {
            type : 'value',
            boundaryGap : [ 0, '100%' ],
            min : function(value) {
              return (value.min * 10000 * 98 / 1000000).toFixed(4);
            },
            max : function(value) {
              return (value.max * 10000 * 102 / 1000000).toFixed(4);
            },
            axisLine: {
              show: false
            },
            axisTick: {
              show: false
            },
            splitLine: {
              lineStyle: {
                type: 'dashed'
              }
            }
          },/*
          dataZoom : [
              {
                type : 'inside',
                zoomOnMouseWheel : false,
                moveOnMouseMove : false,
                preventDefaultMouseMove : false,
                start : 0,
                end : 100
              },
              {
                type : 'slider',
                start : 0,
                end : 100,
                handleIcon : 'M10.7,11.9v-1.3H9.3v1.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4v1.3h1.3v-1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7V23h6.6V24.4z M13.3,19.6H6.7v-1.4h6.6V19.6z',
                handleSize : '80%',
                handleStyle : {
                  color : '#fff',
                  shadowBlur : 3,
                  shadowColor : 'rgba(0, 0, 0, 0.6)',
                  shadowOffsetX : 2,
                  shadowOffsetY : 2
                }
              } ],*/
          series : lines
        });
        myChart.clear();
        myChart.setOption(option);
      }
    },
    //升序排序
    sortUp: function (a, b) {
      var c = a[this.compare];
      var d = b[this.compare];
      if (this.isZh) {
        return c.localeCompare(d, 'zh');
      }else {
        return c-d;       
      }
    },
    //降序排序
    sortDown: function (a, b) {
      var c = a[this.compare];
      var d = b[this.compare];
      if (this.isZh) {
        return d.localeCompare(c, 'zh');
      }else {
          return d-c;
      }
    },
    //点击排序
    sortTable: function (e) {
      var $this = $(e.currentTarget);
      $this.parents('table').find('i.active').removeClass('active');
      $this.siblings('th').data('sort', 'none');
      if ($this.data('sort') == 'up') {
        $this.data('sort', 'none');
      }else if ($this.data('sort') == 'down') {
        $this.data('sort', 'up');
        $this.children('i.fa-sort-up').addClass('active');
      }else {
        $this.data('sort', 'down');
        $this.children('i.fa-sort-down').addClass('active');
      }

      var data = this[$this.parents('table').data('sortName')];
      var showNum = parseInt($this.parents('.model-content').siblings('.table-foot').find('.show-num').val());
      var currentPage = parseInt($this.parents('.model-content').siblings('.table-foot').find('.current-page').val());
      var min = showNum * (currentPage - 1);
      var max = showNum * currentPage;
      if (max > data.length) {
        max = data.length;
      }
      this.compare = $this.data('compare');
      this.isZh = $this.data('zh');
      var $tbody = $this.parents('table').children('tbody');
      var arr = data.slice(min, max);
      if ($this.data('sort') == 'down') {
        arr.sort($.proxy(this.sortDown, this));
      }else if ($this.data('sort') == 'up') {
        arr.sort($.proxy(this.sortUp, this));
      }
      var d = {result: arr};
      var $tpl = $('#' + $this.parents('table').data('template')).html();
      var html = Mustache.render($tpl, d);
      $tbody.html(html);
    },
    //初始化分页
    initPaging: function(data){
      var page = {
        data: data,
        total: data.length,
        nums: 10,
        curPage: 1
      };
      this.page = page;
      this.setPageNums();
    },
    showPageData: function(){
      var page = this.page;
      var array = [];
      for(var i=(page.curPage-1)*page.nums; i < page.curPage*page.nums && i < page.total; i++){
        array.push(page.data[i]);
      }
      
      $.each(array, function (i) {
          this.index = i+1;
      });
      var d = {result: array};
      var $tpl = $('#' + this.template).html();
      var html = Mustache.render($tpl, d);
      $('#tbody').html(html);
      $('#tbody').parents('table').data('sortName', 'sortTableData');
      $('#tbody').parents('table').data('template', this.template);
      
      $('.records').html('<p>显示<span>' + ((page.curPage-1)*page.nums+1) + '</span>到<span>' + (page.curPage*page.nums>page.total?page.total:page.curPage*page.nums) + '</span>,共<span>' + page.total + '</span>记录</p>');
      $('.current-page').val(this.page.curPage);
    },
    showNextPage: function(){
      var page = this.page;
      var totalPages = page.total / page.nums;
      if(totalPages > parseInt(totalPages)) totalPages = parseInt(totalPages) + 1;
      else totalPages = parseInt(totalPages);
      
      if(page.curPage < totalPages) page.curPage++;
      this.showPageData();
    },
    showPrePage: function(){
      var page = this.page;
      if(page.curPage > 1) page.curPage--;
      this.showPageData();
    },
    setPageNums: function(e){
      var nums = $('select.show-num').val();
      var page = this.page;
      page.nums = nums;
      var totalPages = page.total / page.nums;
      if(totalPages > parseInt(totalPages)) totalPages = parseInt(totalPages) + 1;
      else totalPages = parseInt(totalPages);
      $('.total-page').text(totalPages);
      this.showFirstPage();
    },
    showFirstPage: function(){
      this.page.curPage = 1;
      this.showPageData();
    },
    showLastPage: function(){
      var page = this.page;
      var totalPages = page.total / page.nums;
      if(totalPages > parseInt(totalPages)) totalPages = parseInt(totalPages) + 1;
      else totalPages = parseInt(totalPages);
      
      page.curPage = totalPages;
      this.showPageData();
    },
    //勾选框点选
    checkboxChange: function (e) {
      var $this = $(e.currentTarget);
      $this.toggleClass('fa-square').toggleClass('fa-check-square');
    },
    //初始化select2控件
    initSelect2: function () {
      $('.select2').select2({
        width: '160px'
      });
    },
    // 初始化时间插件
    initDatePlug : function() {
      $("#begT").datepicker({
        defaultDate : '',
        changeMonth : true,
        changeYear : true,
        autoclose: true,
        format: "yyyy-mm-dd",
        language: "zh-CN"
      });
      $("#endT").datepicker({
        defaultDate : '',
        changeMonth : true,
        changeYear : true,
        autoclose: true,
        format: "yyyy-mm-dd",
        language: "zh-CN"
      });
    },
    //获取页面数据
    getPageData: function() {
      var data = [
        {
          '产品名称': '招商财富资产理财产品1号',
          '产品类型': '固定收益',
          '期限': '3个月',
          '规模': '1亿',
          '风险等级': 'R2'
        },
        {
          '产品名称': '招商财富资产理财产品2号',
          '产品类型': '固定收益',
          '期限': '3个月',
          '规模': '1亿',
          '风险等级': 'R2'
        },
        {
          '产品名称': '招商财富资产理财产品3号',
          '产品类型': '固定收益',
          '期限': '3个月',
          '规模': '1亿',
          '风险等级': 'R2'
        },
        {
          '产品名称': '招商财富资产理财产品4号',
          '产品类型': '固定收益',
          '期限': '3个月',
          '规模': '1亿',
          '风险等级': 'R2'
        },
        {
          '产品名称': '招商财富资产理财产品5号',
          '产品类型': '固定收益',
          '期限': '3个月',
          '规模': '1亿',
          '风险等级': 'R2'
        },
        {
          '产品名称': '招商财富资产理财产品6号',
          '产品类型': '固定收益',
          '期限': '3个月',
          '规模': '1亿',
          '风险等级': 'R2'
        },
        {
          '产品名称': '招商财富资产理财产品7号',
          '产品类型': '固定收益',
          '期限': '3个月',
          '规模': '1亿',
          '风险等级': 'R2'
        },
        {
          '产品名称': '招商财富资产理财产品8号',
          '产品类型': '固定收益',
          '期限': '3个月',
          '规模': '1亿',
          '风险等级': 'R2'
        },
        {
          '产品名称': '招商财富资产理财产品9号',
          '产品类型': '固定收益',
          '期限': '3个月',
          '规模': '1亿',
          '风险等级': 'R2'
        },
        {
          '产品名称': '招商财富资产理财产品1号',
          '产品类型': '固定收益',
          '期限': '3个月',
          '规模': '1亿',
          '风险等级': 'R2'
        },
        {
          '产品名称': '招商财富资产理财产品2号',
          '产品类型': '固定收益',
          '期限': '3个月',
          '规模': '1亿',
          '风险等级': 'R2'
        },
        {
          '产品名称': '招商财富资产理财产品3号',
          '产品类型': '固定收益',
          '期限': '3个月',
          '规模': '1亿',
          '风险等级': 'R2'
        },
        {
          '产品名称': '招商财富资产理财产品4号',
          '产品类型': '固定收益',
          '期限': '3个月',
          '规模': '1亿',
          '风险等级': 'R2'
        },
        {
          '产品名称': '招商财富资产理财产品5号',
          '产品类型': '固定收益',
          '期限': '3个月',
          '规模': '1亿',
          '风险等级': 'R2'
        },
        {
          '产品名称': '招商财富资产理财产品6号',
          '产品类型': '固定收益',
          '期限': '3个月',
          '规模': '1亿',
          '风险等级': 'R2'
        }
      ];
      this.sortTableData = data;
      this.initPaging(data);
    }
  };

  pageApp.init();
});